﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace WeChatRobotSDKCommon.Helper
{
   public class RemoteImageCatchUtil
    {
        private static string[] ImageExts = new[] { "jpg", "jpeg", "png", "bitmap", "gif" };

        public static string Catch(string remoteImagePath, string saveFolder, int timeout = 2000)
        {
            try
            {
                var request = WebRequest.Create(remoteImagePath) as HttpWebRequest;
                request.Timeout = timeout > 0 ? timeout : 1000;
                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception("远程访问失败");
                    }
                    else
                    {
                        var ext = GetImageExtension(response.ContentType).ToLower();
                        if (!ImageExts.Contains(ext))
                        {
                            throw new Exception("非图片文件");
                        }

                        var stream = response.GetResponseStream();
                        var buffer = new byte[2048];
                        int count;
                        using (var ms = new MemoryStream())
                        {
                            while ((count = stream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                ms.Write(buffer, 0, count);
                            }

                            if (!Directory.Exists(saveFolder))
                            {
                                Directory.CreateDirectory(saveFolder);
                            }
                            var imageName = Path.GetRandomFileName() + "." + ext;
                            var imagePath = Path.Combine(saveFolder, imageName);
                            var image = new Bitmap(ms);
                            image.Save(imagePath);
                            return imageName;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static string GetImageExtension(string contentType)
        {
            if (contentType.StartsWith("image"))
            {
                return contentType.Split(@"/").Last();
            }
            return string.Empty;
        }
    }
}
